<template>
  <div id="picture-upload">
    <a-upload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :custom-request="handleUpload"
    >
      <img v-if="picture?.url" :src="picture?.url"  alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击拖拽上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref, toRef, toRefs } from 'vue'
import { message } from 'ant-design-vue'
import { EditOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { uploadPictureUsingPost } from '@/request/api/pictureController'
import ImageCropper from '@/components/ImageCropper.vue'
import * as url from 'node:url'

// Props类型
interface Props {
  spaceId?: any
  picture?: API.PictureVO
  onSuccess?: (newPicture: API.PictureVO) => void
}
const props = defineProps<Props>()
const loading = ref<boolean>(false)
// 有效的文件类型
const validFileTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
// 有效的文件大小
const validFileSize = 30 * 1024 * 1024 // 30MB
// 上传前的钩子函数
// 这里可以做一些文件类型和大小的校验
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isValidType = validFileTypes.includes(file.type)
  const isValidSize = file.size <= validFileSize
  if (!isValidType) {
    message.error('请上传正确的图片格式')
    return false
  }
  if (!isValidSize) {
    message.error('请上传小于30MB的图片')
    return false
  }
  return true
}
// 上传成功的钩子函数
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    // 有图片就是修改，没有图片就是添加
    const params: API.uploadPictureUsingPOSTParams = props.picture ? { id: props.picture.id } : {}
    params.spaceId=props.spaceId;
    let { data: res } = await uploadPictureUsingPost(params, {}, file)
    if (res.code === 0 && res.data) {
      // 上传成功
      message.success('上传成功')
      // 将信息返回给父组件
      props.onSuccess?.(res.data)
    } else {
      // 上传失败
      message.error('上传失败' + res.message)
    }
  } catch (e) {
    // 上传失败
    message.error('上传失败' + e)
  } finally {
    loading.value = false
  }
}

</script>
<style lang="less" scoped>
#picture-upload :deep(.ant-upload) {
  // 穿透样式覆盖里面的样式
  width: 100% !important;
  height: 100% !important;
  min-width: 152px;
  min-height: 152px;
  img {
    align-content: center;
    max-width: 100%;
    max-height: 480px;
  }
  .ant-upload-select-picture-card {
    i {
      font-size: 32px;
      color: #999;
    }
    .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
}
</style>
